<?php

namespace app\models;
use Yii;
use yii\base\Exception;
use yii\data\Pagination;
use yii\db\ActiveRecord;


class Ruku extends ActiveRecord
{


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [

            
            ['rkorder', 'required'],
            ['rk_name','string'],
            ['iccid_list', 'validatelist'],
            [['iccid_start', 'iccid_end'], 'validatesmall'],
            ['batch_no', 'string', 'max' => 32],
        ];
    }
    public function validatesmall($attribute, $params){
        $str = $this->iccid_start;
        if(strlen($str) != 20){
            $this->addError($attribute,"请填写20位iccid号码");
        }
        $start = substr($this->iccid_start, 5);
        $end = substr($this->iccid_end, 5);
        
        if($this->iccid_start > $this->iccid_end){
            $this->addError($attribute, "开始号码不能大于结束号码.");
        }
        $small = ($end - $start)+1;
        if ($this->number != $small){
            $this->addError($attribute,"iccid数量不对,请认真核对");
        }
    }
    public function validatelist($attribute,$params){
        $str = str_replace(array("\r\n", "\r", "\n"), "", $this->iccid_list);
        $list = strlen($str) / 20;
        
        if($this->number != $list){
            $this->addError($attribute,"iccid数量不对,请认真核对");
        }
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            
            'rkorder'     => '订单号',
            'rk_name' => '采购项目名称',
            'number'  => '数量',
            'iccid_list' => 'ICCID列表',
            'iccid_start' => 'ICCID开始号码',
            'iccid_end' => 'ICCID结束号码',
            'batch_no' => '批次号',

        ];
    }


    /**
     * 生成新的批次号
     * @param integer $mid 管理用户编号，0表示系统自动添加
     * @return string
     */
    public static function generateBatchNo($mid = 0)
    {
        return date('YmdHis') . Util::randomStr(6) . $mid;
    }
    /*
        *关联接口
     */
    public function getApi(){
        return $this->hasOne(Api::class, ['id' => 'api_id']);
    }
    /**
     * 关联运营商
     * @return \yii\db\ActiveQuery
     */
    public function getIsp()
    {
        return $this->hasOne(Isp::class, ['id' => 'isp_id']);
    }
    public function getPackageIsp(){
        return $this->hasOne(PackageIsp::class, ['id' => 'package_id']);
    }
    /**
     * 关联套餐
     * @return \yii\db\ActiveQuery
     */
    // public function getPackage()
    // {
    //     return $this->hasOne(Package::class, ['id' => 'package_id']);
    // }

    
    
}

